package com.ruoyi.keep.service.impl;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ruoyi.common.constant.CommonConstant;
import com.ruoyi.keep.domain.*;
import com.ruoyi.keep.mapper.*;
import com.ruoyi.keep.service.IUserBuyRechargeCardService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.keep.service.IReservationService;

/**
 * 团课预约管理Service业务层处理
 *
 * @author wangziyang
 * @date 2024-08-13
 */
@Service
public class ReservationServiceImpl implements IReservationService {
    @Autowired
    private ReservationMapper reservationMapper;
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private UserBuyRechargeCardMapper userBuyRechargeCardMapper;
    @Autowired
    private OrderDetailMapper orderDetailMapper;
    @Autowired
    private UserBuyNumberCardMapper userBuyNumberCardMapper;

    /**
     * 查询团课预约管理
     *
     * @param id 团课预约管理主键
     * @return 团课预约管理
     */
    @Override
    public Reservation selectReservationById(Long id) {
        return reservationMapper.selectReservationById(id);
    }

    /**
     * 查询团课预约管理列表
     *
     * @param reservation 团课预约管理
     * @return 团课预约管理
     */
    @Override
    public List<Reservation> selectReservationList(Reservation reservation) {
        return reservationMapper.selectReservationList(reservation);
    }

    /**
     * 新增团课预约管理
     *
     * @param reservation 团课预约管理
     * @return 结果
     */
    @Override
    public int insertReservation(Reservation reservation) {
        return reservationMapper.insertReservation(reservation);
    }

    /**
     * 修改团课预约管理
     *
     * @param reservation 团课预约管理
     * @return 结果
     */
    @Override
    public int updateReservation(Reservation reservation) {
        return reservationMapper.updateReservation(reservation);
    }

    /**
     * 批量删除团课私教预约管理
     *
     * @param ids 需要删除的团课预约管理主键
     * @return 结果
     */
    @Override
    public int deleteReservationByIds(Long[] ids) {
//        删除订单
        List<Reservation> list = reservationMapper.selectBatchIds(Arrays.stream(ids)
                .collect(Collectors.toList()));
        list.forEach(reservation -> {
            orderMapper.deleteOrderById(reservation.getOrderId());
        });
//        删除预约
        return reservationMapper.deleteReservationByIds(ids);
    }

    /**
     * 删除团课私教预约管理信息
     *
     * @param id 团课预约管理主键
     * @return 结果
     */
    @Override
    public int deleteReservationById(Long id) {
//        删除订单
        Reservation reservation = reservationMapper.selectById(id);
        orderMapper.deleteOrderById(reservation.getOrderId());
//        删除预约
        return reservationMapper.deleteReservationById(id);
    }

    //  团课预约查询--全部
    @Override
    public Map<String, Object> selectTeamReservationList(Integer pageNum, Integer pageSize, Reservation reservation) {
        PageHelper.startPage(pageNum, pageSize);
        List<Reservation> list = reservationMapper.selectTeamReservationList(reservation);
        //分页信息对象
        PageInfo<Reservation> pageInfo = new PageInfo<>(list);
        //封装到map集合当中
        Map<String, Object> map = new HashMap<>();
        map.put(CommonConstant.PAGE_LIST, list);
        map.put(CommonConstant.PAGE_NUM, pageInfo.getPageNum());
        map.put(CommonConstant.PAGE_SIZE, pageInfo.getPageSize());
        map.put(CommonConstant.TOTAL, pageInfo.getTotal());
        map.put(CommonConstant.PAGE_TOTAL, pageInfo.getPages());
        return map;
    }

    //后台同意退款--团课和私课
    @Override
    public int updateReservationOrderStatus(Long id) {
        int k = 0, s = 0;//退款金额判断,判断次数判断

//      查询得到预约和订单的实体类
        Reservation reservation = reservationMapper.selectById(id);
        Order order = orderMapper.selectById(reservation.getOrderId());
        OrderDetail orderDetail = orderDetailMapper.selectOne(new QueryWrapper<OrderDetail>().eq("order_id", order.getId()));

        //退款金额判断--微信支付和充值卡充值
        if (order.getOrderPayment() == 0 || order.getOrderPayment() == 1) {
            //退款50%
            Double money = new BigDecimal(Double.toString(order.getOrderPrice() / 2)).setScale(2, RoundingMode.HALF_UP).doubleValue();
            System.out.println(money);
            UserBuyRechargeCard userBuyRechargeCard = userBuyRechargeCardMapper.selectOne(new QueryWrapper<UserBuyRechargeCard>().eq("user_id", order.getUserId()));
            //拿到现有金额并加上退款金额
            userBuyRechargeCard.setResiduePrice(userBuyRechargeCard.getResiduePrice() + money);
            k = userBuyRechargeCardMapper.updateUserBuyRechargeCard(userBuyRechargeCard);

            //退款次数判断--次数卡支付--退款50%次数
        } else if (order.getOrderPayment() == 2) {
            Integer count = (int) Math.round(order.getOrderPrice() / 50);
            UserBuyNumberCard userBuyNumberCard = userBuyNumberCardMapper.selectOne(new QueryWrapper<UserBuyNumberCard>().eq("user_id", order.getUserId()));
//            判断是否为空
            if (userBuyNumberCard.getResidueNumber() == null) {
                userBuyNumberCard.setResidueNumber(0);
            }
            //退款次数的50%,如果次数小于等于1，退款1次，大于1的，退款次数的50%
            if (count <= 1) {
                userBuyNumberCard.setResidueNumber(userBuyNumberCard.getResidueNumber() + 1);
            } else {
                userBuyNumberCard.setResidueNumber(userBuyNumberCard.getResidueNumber() + count / 2);
            }
            s = userBuyNumberCardMapper.update(userBuyNumberCard, new UpdateWrapper<UserBuyNumberCard>().eq("id", userBuyNumberCard.getId()));

        }
        // 两个更新操作--订单3和预约4,以及订单的更新时间
        int i = reservationMapper.update(null, new UpdateWrapper<Reservation>().eq("id", id).set("reservation_status", 3));
        int j = orderMapper.update(null, new UpdateWrapper<Order>().eq("id", reservation.getOrderId()).set("order_status", 4).set("order_update_time", new Date()));
        if (i + j + k == 3 || i + j + s == 3) {
            return 3;
        }
        return 0;
    }

    //后台不同意退款
    @Override
    public int updateReservationOrderStatusRefuse(Long id) {
        Reservation reservation = reservationMapper.selectById(id);
        // 两个更新操作--订单改为已支付和预约代签到
        int i = reservationMapper.update(null, new UpdateWrapper<Reservation>().eq("id", id).set("reservation_status", 1));
        int j = orderMapper.update(null, new UpdateWrapper<Order>().eq("id", reservation.getOrderId()).set("order_status", 1).set("order_update_time", new Date()));
        if (i + j == 2) {
            return i + j;
        }
        return 0;
    }

    //  私课预约查询--全部
    @Override
    public List<Reservation> selectPersonalReservationList(Reservation reservation) {
        return reservationMapper.selectPersonalReservationList(reservation);
    }

    //  私课预约查询--根据用户id
    @Override
    public List<Reservation> selectPersonalReservationListByUserId(Reservation reservation) {
        return reservationMapper.selectPersonalReservationByUserId(reservation);
    }

    /*
     * 预约申请退款
     * */
    @Override
    public int updateReservationStatus(Reservation reservation) {
        int j = reservationMapper.update(null, new UpdateWrapper<Reservation>().eq("id", reservation.getId()).set("reservation_status", 2));
        int k = orderMapper.update(null, new UpdateWrapper<Order>().eq("id", reservation.getOrderId()).set("order_status", 3));
        return (k + j)==2?2:0;
    }
    /*
     * 预约签到
     * */
    @Override
    public int updateSignReservationStatus(Reservation reservation) {
        int j = reservationMapper.update(null, new UpdateWrapper<Reservation>().eq("id", reservation.getId()).set("reservation_status", 0));
        int k = orderMapper.update(null, new UpdateWrapper<Order>().eq("id", reservation.getOrderId()).set("order_status", 2));
        return (k + j)==2?2:0;
    }
    /*
     * 团课预约查询--根据用户id查询
     * */
    @Override
    public List<Reservation> selectTeamReservationListByUserId(Reservation reservation) {
        return reservationMapper.selectTeamReservationListByUserId(reservation);
    }


}
